package com.ray.util;

import java.util.HashMap;

/**
 * Ret 用于返回值封装，也用于服务端与客户端的 json 数据通信
 */
public class Ret extends HashMap {

    private static final long serialVersionUID = -2150729333382285526L;

    /**
     * 状态
     */
    static String STATE = "code";
    static Object STATE_OK = 200;
    static int STATE_FAIL = 1;
    /**
     * 数据
     */
    static String DATA = "data";
    static boolean dataWithOkState = false;			// data(Object) 方法伴随 ok 状态

    /**
     * 消息
     */
    static String MSG = "msg";

    public static Ret ok() {
        return new Ret().setOk();
    }

    public static Ret ok(String msg) {
        return new Ret().setOk()._setMsg(msg);
    }

    public static Ret ok(Object key, Object value) {
        return new Ret().setOk().set(key, value);
    }
    public static Ret fail(int code) {
        return new Ret().setFail(code);
    }

    public static Ret fail(String msg) {
        return new Ret().setFail(STATE_FAIL)._setMsg(msg);
    }

    public static Ret fail(Object key, Object value) {
        return new Ret().setFail(STATE_FAIL).set(key, value);
    }
    public Ret setOk() {
        return _setState(STATE_OK);
    }

    public Ret setFail(int code) {
        return _setState(code);
    }

    protected Ret _setState(Object value) {
        super.put(STATE, value);
        return this;
    }
    protected Ret _setData(Object data) {
        super.put(DATA, data);
        if (dataWithOkState) {
            _setState(STATE_OK);
        }
        return this;
    }

    // 避免产生 setter/getter 方法，以免影响第三方 json 工具的行为
    protected Ret _setMsg(String msg) {
        super.put(MSG, msg);
        return this;
    }

    public Ret set(Object key, Object value) {
        super.put(key, value);
        return this;
    }

    public Ret setJson(Object key,Object value){
        super.put(key, JsonKit.toJson(value));
        return this;
    }
}
